package howl.Twitter;

import java.util.List;

import howl.model.Model;
import howl.types.HowlUser;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;

import com.google.appengine.api.users.User;

public class EnableTwitter {

	public static String enableTwitter(User user) {
		System.out.println(user);
		System.out.println(user.getEmail());

		Model m = new Model(Model.getHowlUserfromUser(user));
		HowlUser s = m.getHowlUser();

		Twitter t = TwitterProvider.getTwitter();
		// t.setOAuthConsumer();

		// RequestToken requestToken = TwitterProvider.getToken("http://uowapplication.appspot.com/Auth/TwitterConsumer.jsp");
		RequestToken requestToken = TwitterProvider.getToken("http://localhost:8080/Auth/TwitterConsumer.jsp");
		s.setTwitterToken(requestToken.getToken());
		s.setTwitterTokenSecret(requestToken.getTokenSecret());
		m.getPm().close();
		return requestToken.getAuthorizationURL();
	}

	public static boolean recieveTwitterUser(User user, String oauth_veri) {
		System.out.println(oauth_veri);
		System.out.println(user);
		Model m = new Model(Model.getHowlUserfromUser(user));
		try {

			HowlUser s = m.getHowlUser();
			Twitter t = TwitterProvider.getOauthTwitter();
			String token = s.getTwitterToken();
			String tokenSecret = s.getTwitterTokenSecret();
			/*
			 * System.out.println("token: " + token);
			 * System.out.println("token secret: " + tokenSecret);
			 */
			AccessToken accessToken = t.getOAuthAccessToken(token, tokenSecret,
					oauth_veri);

			
			s.setTwitterName(t.verifyCredentials().getScreenName());
			s.setTwitterToken(accessToken.getToken());
			s.setTwitterTokenSecret(accessToken.getTokenSecret());
			s.setTwitterisConfigured(true);
			TwitterProvider.followMe(s);
			m.getPm().close();
			if (s.isYourFlowingData() && !s.isYourFlowingDataisConfigured()) {
				m = new Model(Model.getHowlUserfromUser(user));
				s = m.getHowlUser();
				Yfd.followYFD(s);
				s.setYourFlowingDataisConfigured(true);
				m.getPm().close();
			}
			
		//	TwitterProvider.followMe(s);
			//m.getPm().close();

		} catch (TwitterException e) {
			e.printStackTrace();
			boolean y = true;
			return false;
		}

		return true;
	}

	public static void testTwitteroAuth(User user) {
		Model m = new Model(Model.getHowlUserfromUser(user));
		HowlUser hu = m.getHowlUser();

		Twitter t = TwitterProvider.getTwitter();
		t.setOAuthAccessToken(hu.getTwitterToken(), hu.getTwitterTokenSecret());
		/*try {
			//t.updateStatus("this is a test for twitter oAuth user");
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
	}
}
